import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
from sklearn.metrics import silhouette_score,adjusted_rand_score,accuracy_score

# Generate synthetic data
X, y = make_blobs(n_samples=100, n_features=2, centers=3)

# Print the shapes of X and y
print("Shape of X:", X.shape)
print("Shape of y:", y.shape)

# Plot the scatter plot
plt.scatter(X[:, 0], X[:, 1], c=y)
# plt.xlabel('Feature 1')
# plt.ylabel('Feature 2')
# plt.title('Scatter Plot of Generated Data')
# plt.colorbar(label='Cluster Label')
plt.show()
# k-means聚类 K是聚类个数
# 如何确定K值：手肘法（肘部法）
# 根据k和最后的聚类效果（距离平方和），共同绘制折线图，从而判断k的最佳值
dis = []
for k in range(1,50):
    km = KMeans(n_clusters=k)
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.15)
    km.fit(X_train)
    dis.append(km.inertia_)
    print(km.cluster_centers_)
    # sil_score = silhouette_score(y_test, km.predict(X_test))
    # print(f'Silhouette Score: {sil_score:.2f}')

    # Adjusted Rand Index
    ari = adjusted_rand_score(y_test, km.predict(X_test))
    acc = accuracy_score(y_test,km.predict(X_test))
    print(f"ari:{ari}")
    print(f"acc:{acc}")
    print(km.predict(X_test))
    print(y_test)
    # 聚类算法预测的标签不是有监督监督学习里的标签的含义
plt.plot(range(1,50),dis)
plt.show()